package public

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

type DecryptRequest struct {
	Code          string `json:"code"`
	EncryptedData string `json:"encryptedData"`
	IV            string `json:"iv"`
}

type WXSessionResponse struct {
	OpenID     string `json:"openid"`
	SessionKey string `json:"session_key"`
	UnionID    string `json:"unionid"`
	ErrCode    int    `json:"errcode"`
	ErrMsg     string `json:"errmsg"`
}

func GetPhoneNumber(c *gin.Context) {
	var req DecryptRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "请求参数错误",
		})
		return
	}

	// 在这里设置你的小程序解密秘钥（session_key）
	sessionKeyData, err := GetWxSessionInfo(req.Code)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": -1,
			"msg":  "session_key获取失败",
		})
		return
	}
	sessionKey := sessionKeyData.SessionKey

	encryptedData := req.EncryptedData
	iv := req.IV
	decodedData, err := decryptData(encryptedData, sessionKey, iv)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": -1,
			"msg":  "解密失败",
			"data": sessionKeyData,
		})
		return
	}

	var data map[string]interface{}
	if err := json.Unmarshal(decodedData, &data); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": -1,
			"msg":  "解析数据失败1111",
		}) // 打印解析错误
		log.Println(string(decodedData))
		return
	}
	log.Println(data)
	return
	phoneNumber := data["phoneNumber"].(string)
	c.JSON(http.StatusOK, gin.H{
		"code":        0,
		"msg":         "获取手机号成功",
		"phoneNumber": phoneNumber,
	})
}

// GetWxSessionInfo 获取微信登录凭证校验信息
func GetWxSessionInfo(code string) (*WXSessionResponse, error) {
	appID := "wxf2aa5e767ecfd0e5"                   // 替换为你的小程序 AppID
	appSecret := "52c8e5e2aee4a0f80d0724fb5611f70a" // 替换为你的小程序 AppSecret
	url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appID, appSecret, code)

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var sessionResp WXSessionResponse
	err = json.NewDecoder(resp.Body).Decode(&sessionResp)
	if err != nil {
		return nil, err
	}

	if sessionResp.ErrCode != 0 {
		return nil, fmt.Errorf(sessionResp.ErrMsg)
	}

	return &sessionResp, nil
}

func decryptData(encryptedData, sessionKey, iv string) ([]byte, error) {
	// 解码 sessionKey 和 iv
	key, err := base64.StdEncoding.DecodeString(sessionKey)
	if err != nil {
		return nil, err
	}
	ivBytes, err := base64.StdEncoding.DecodeString(iv)
	if err != nil {
		return nil, err
	}
	encryptedBytes, err := base64.StdEncoding.DecodeString(encryptedData)
	if err != nil {
		return nil, err
	}

	// 创建 AES 密钥块
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	// 创建解密模式
	mode := cipher.NewCBCDecrypter(block, ivBytes)

	// 创建用于存储解密后数据的切片
	decryptedData := make([]byte, len(encryptedBytes))

	// 解密数据
	mode.CryptBlocks(decryptedData, encryptedBytes)

	// 去除 PKCS7 填充
	decryptedData = unpadPKCS7(decryptedData)

	return decryptedData, nil
}

func unpadPKCS7(data []byte) []byte {
	padding := int(data[len(data)-1])
	return data[:len(data)-padding]
}
